package com.demo.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Created by Zhang Fan on 2018/1/5.
 */
@Configuration
@MapperScan(basePackages = "com.demo.mybatis.dao2",sqlSessionTemplateRef ="test1SqlSessionTemplate" )
public class DataSource2Config {

    @Autowired
    private DB2 db2;

    @Bean(name = "datasource2")
    public DataSource primaryDataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(db2.getUrl());
        datasource.setUsername(db2.getUsername());
        datasource.setPassword(db2.getPassword());
        datasource.setDriverClassName(db2.getDriverClassName());
        //configuration
        datasource.setInitialSize(db2.getInitialSize());
        datasource.setMinIdle(db2.getMinIdle());
        datasource.setMaxActive(db2.getMaxActive());
        datasource.setMaxWait(db2.getMaxWait());
        try {
            datasource.setFilters(db2.getFilters()); //sql监控
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return datasource;
    }


    @Bean(name = "test1SqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("datasource2") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/db2/*.xml"));
        return bean.getObject();
    }



    @Bean(name = "test1SqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }




}
